package http

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

type MyHttpClient struct {
	Url          string            //请求地址
	Params       map[string]any    //请参数
	ParamsReader io.Reader         //
	Header       map[string]string //请求头
	Response     *http.Response    //响应
}

//const kContentType = "Content-Type"

const (
	ContentTypeJSON      string = "application/json"
	ContentTypeXML       string = "application/xml"
	ContentTypeURLEncode string = "application/x-www-form-urlencoded"
	ContentTypeHTML      string = "text/html"
	ContentTypeText      string = "text/plain"
	ContentTypeMultipart string = "multipart/form-data"
)

const MYGET = "GET"
const MYPOST = "POST"

func NewMyHttpClient(url string, params map[string]any) *MyHttpClient {
	if params == nil {
		params = map[string]any{}
	}
	return &MyHttpClient{Url: url, Params: params, Header: map[string]string{}}
}

func (cl *MyHttpClient) SetFieldValue(key string, value any) {
	cl.Params[key] = value
}

func (cl *MyHttpClient) SetUrl(url string) {
	cl.Url = url
}
func (cl *MyHttpClient) SetHeader(key string, value string) {
	cl.Header[key] = value
}

func (cl *MyHttpClient) Request(method string) string {
	var (
		rep     []byte
		err     error
		request *http.Request
	)
	switch method {
	case MYGET:
		request, err = http.NewRequest(MYGET, cl.Url, cl.ParamsReader)
		if err != nil {
			panic(err)
		}
		break
	case MYPOST:
		request, err = http.NewRequest(MYPOST, cl.Url, cl.ParamsReader)
		if err != nil {
			panic(err)
		}
		break
	default:
		panic("非法的请求方法")
	}
	if len(cl.Header) > 0 {
		for key, item := range cl.Header {
			request.Header.Add(key, item)
		}
	}
	client := http.Client{
		Timeout: 2 * time.Duration(time.Second),
	}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	cl.Response = response
	defer response.Body.Close()
	rep, err = ioutil.ReadAll(response.Body)
	if err != nil && err != io.EOF {
		panic(err)
	}

	return string(rep)
}

func (cl *MyHttpClient) SetParamsReader(params string) {
	if params == "" {
		cl.ParamsReader = bytes.NewBuffer([]byte{})
	} else {
		cl.ParamsReader = bytes.NewBuffer([]byte(params))
	}

}

// 格式化请求参数
func (cl *MyHttpClient) MarshalParams(formatType string) {
	var (
		paramByte []byte
		err       error
	)
	if len(cl.Params) > 0 {
		switch formatType {
		case "json":
			paramByte, err = json.Marshal(cl.Params)
			break
		default:
			panic("未知的格式化类型")
		}
		if err != nil {
			panic(err)
		}
	} else {
		paramByte = []byte{}
	}

	cl.ParamsReader = bytes.NewBuffer(paramByte)

}
